package com.ruiyi.utils;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmailUtil implements Runnable {
    private String address;
    private String code;

    public SendEmailUtil(String address, String code) {
        this.address = address;
        this.code = code;
    }

    public void run() {
        try {
            sendMessage(this.address,this.code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void sendMessage(String address,String code) throws Exception {
        Properties props = new Properties();
        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        // 设置环境信息
        Session session = Session.getInstance(props);
        // 创建邮件对象
        Message msg = new MimeMessage(session);
        // 设置邮件标题
        msg.setSubject("瑞翼CRM后台验证码");
        // 设置邮件内容
        msg.setText("验证码："+code);
        // 设置发件人,并设置标头
        msg.setFrom(new InternetAddress("1597156884@qq.com", "我们是管理员"));
        // 获得链接
        Transport transport = session.getTransport();
        // 连接邮件服务器，这里设置发件人的邮箱和密码。如果是163的邮箱就把"smtp.qq.com"改成"smtp.163.com"
        //其他的同理，不然连接不到邮件服务器
        /*graukitbgjmkfjcb*/
        transport.connect("smtp.qq.com", "1597156884@qq.com", "graukitbgjmkfjcb");
        // 发送邮件
        transport.sendMessage(msg, new Address[] { new InternetAddress(address) });
        // 关闭连接
        transport.close();
    }
}
